package com.bamboo.mall.product.exception;

import com.bamboo.common.exception.BizCodeEnum;
import com.bamboo.common.utils.R;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * @author : bamboo
 * @date : 2020-04-09
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.bamboo.mall.product.controller")
public class MallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e) {
        Map<String, String> map = Maps.newHashMap();

        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach(objectError -> {
            String objectName = objectError.getField();
            String defaultMessage = objectError.getDefaultMessage();
            map.put(objectName, defaultMessage);
        });

        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handlerValidException(Throwable e) {
        log.error("出现问题:{}, 异常类:{}", e.getMessage(), e.getClass());
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
